const formatTime = date => {
  date = date? date : new Date()
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

/**
 * 对象转URL
 */
const urlEncode = data => {
  var _result = [];
  for (var key in data) {
    var value = data[key];
    if (value.constructor == Array) {
      value.forEach(_value => {
        _result.push(key + "=" + _value);
      });
    } else {
      _result.push(key + '=' + value);
    }
  }
  return _result.join('&');
}

/**
 * 时间转时辰
 * @param {int} data 需要转时辰的时间
 */
const time2Lunar = (data) => {
  let hour = data || getCurHour()
  let lunarHour = ''
  if(hour === 23 || hour === 0) {
    lunarHour = '子时'
  }
  else if(hour === 1 || hour === 2) {
    lunarHour = '丑时'
  }
  else if(hour === 3 || hour === 4) {
    lunarHour = '寅时'
  }
  else if(hour === 5 || hour === 6) {
    lunarHour = '卯时'
  }
  else if(hour === 7 || hour === 8) {
    lunarHour = '辰时'
  }
  else if(hour === 9 || hour === 10) {
    lunarHour = '巳时'
  }
  else if(hour === 11 || hour === 12) {
    lunarHour = '午时'
  }
  else if(hour === 13 || hour === 14) {
    lunarHour = '未时'
  }
  else if(hour === 15 || hour === 16) {
    lunarHour = '申时'
  }
  else if(hour === 17 || hour === 18) {
    lunarHour = '酉时'
  }
  else if(hour === 19 || hour === 20) {
    lunarHour = '戊时'
  }
  else if(hour === 21 || hour === 22) {
    lunarHour = '亥时'
  }

  return lunarHour
}

const getCurHour = () => {
  let date = new Date()
  let hour = date.getHours()
  return hour
}

module.exports = {
  formatTime,
  urlEncode,
  time2Lunar
}
